/*********************************************************************************
 *Copyright(C),1996-2022,ChenJiehong
 *FileName:  swtimer.c
 *Author: ChenJiehong
 *Version:  V1.0
 *Date: 2023-04-18
 ****************************************Includes***********************************/
#include "swtimer.h"


/***************************************Variables***********************************/
static SoftTimer_t l_SoftTimer[SWTIMER_NR_OF];

/***************************************Functions***********************************/

void SoftTimer_Init(void)
{
		for ( uint8_t index = 0U; index < SWTIMER_NR_OF; index++ )
		{
				l_SoftTimer[index].u32interval = 0;
				l_SoftTimer[index].mode = TIMER_ONE_SHOT_MODE;
				l_SoftTimer[index].u32Current = 0;
				l_SoftTimer[index].u8Triggered = 0;
		}
}

void swtimer_register(uint8_t index, uint32_t interval, SoftTimerMode_t SoftTimerMode)
{
    if ( index < SWTIMER_NR_OF )
    {
        l_SoftTimer[index].mode = SoftTimerMode;
        l_SoftTimer[index].u32interval = interval;
        l_SoftTimer[index].u8Triggered = 0;
    }
}

void swtimer_start(uint8_t index)
{
    l_SoftTimer[index].u32Current = l_SoftTimer[index].u32interval;
    l_SoftTimer[index].u8Triggered = 0;
}

void swtimer_stop(uint8_t index)
{
    l_SoftTimer[index].u32Current = 0U;
    l_SoftTimer[index].u8Triggered = 0U;
}

uint8_t swtimer_isTriggered(uint8_t index)
{
    uint8_t lb_trigged = 0U;

    if ( l_SoftTimer[index].u8Triggered != 0U )
    {
        l_SoftTimer[index].u8Triggered = 0U;
        lb_trigged = 1U;
    }

    return ( lb_trigged );
}

void SoftTimer_Handler(void)
{
	for (uint32_t index = 0U; index < SWTIMER_NR_OF; index++)
	{
			if (l_SoftTimer[index].u32Current != 0U)
			{
					l_SoftTimer[index].u32Current--;

					if (l_SoftTimer[index].u32Current == 0)
					{
							l_SoftTimer[index].u8Triggered = 1;
							if (l_SoftTimer[index].mode == TIMER_PERIODIC_MODE)
							{
									l_SoftTimer[index].u32Current = l_SoftTimer[index].u32interval;
							}
					}
			}
	}
}


/***************************************END OF FILE*********************************/
